#include <iostream>
#include "TROOT.h"
#include "TTree.h"

#include "IOmanager.h"
#include "Analysis.h"
#include "ConfigParser.h"

/*******************************************************************************
  Verify that file is written correctly
 *******************************************************************************/
void verifyFile(TString s)
{
    // Read from file
    cout<<endl<<"NOW: Verifying file"<<endl<<endl;
    TTree *res = IOmanager::getNtuple(s.Data());
    res->SetScanField(0);
    cout<<"Entries: "<<res->GetEntries()<<endl;
    res->Scan("method:dataprobe:dataselected:sigprobe1:sigselected1:bgdprobe1:bgdselected1:probe_nsig1:probe_nsig_err1:probe_nbgd1:probe_nbgd_err1:selected_nsig1:selected_nsig_err1:selected_nbgd1:selected_nbgd_err1:efficiency:efficiency_err:effic_method","","colsize=11");
}

/*******************************************************************************
  Main - invoking analysis sequence
 *******************************************************************************/
int main(int argc,char **argv)
{
    gROOT->SetBatch(kTRUE);
    IOmanager& IOman = IOmanager::instance();

    if(argc<2)
    {
        cout<<endl<<endl<<"Usage: "<<argv[0]<<" <config_file>"<<endl<<endl;
        exit(-1);
    }

    /*****************************************************************************
      Read configuration file
     *****************************************************************************/
    for(int i=1;i<argc;i++)
    {
        /// Create output file name
        TString filename = argv[i];
        int index = filename.Last('/');
        /// Truncate filename - remove directory name and '.conf' suffix
        filename = filename(index+1,filename.Length()-index-1-5);
        filename+=".root";
        /// Open output file
        IOman.openOutput(filename.Data());

        vector <AnalysisConfig> V = ConfigParser::initialize(ConfigParser::parseConfig(argv[1]));
        for(vector <AnalysisConfig>::iterator it = V.begin();it!=V.end();it++) { ///< Go through all the configuration variations.
            it->print();
            Analysis a(*it);
            a.runAnalysis();
        }
        IOman.closeOutput();
        verifyFile(filename);
    }
    return 0;
}
